<?php
namespace app\controller;


use app\Request;

use app\validate\RoomsPlayerValid as RPlayerValid;

use app\model\Rooms as RoomsModel;
use app\model\RoomsPlayer as RoomsPlayerModel;

use app\service\Geteway as GetewayService;

/**
 * @author yanxusheng <[<ausheng@foxmail.com>]>
 * @datetime 2023/8/8 16:10
 * @content 赛事房间内玩家管理器
 */
class RoomsPlayer extends Communal
{
    /**
     * @param Request $request
     * @param RPlayerValid $valid
     */
    public function create(Request $request, RPlayerValid $valid) {
        if(!$valid->scene('create')->check($request->post())){
            $this->error($valid->getError());
        }
        $room_code = $request->post('room_code');
        $room_pass = $request->post('password');

        // 判断创建过房间没有
        $resp_rooms = RoomsModel::HasCreateRoomByPlayerId($request->usersId);
        if (!$resp_rooms->isEmpty() && $resp_rooms->room_code != $room_code) {
            $this->error("您创建的比赛正在进行，请回到赛场主持比赛", null, 302);
        }

        // 判断是否已经在房间内了
        $resp_r_player = RoomsPlayerModel::HasJoinRoomByPlayerId($request->usersId);
        if (!$resp_r_player->isEmpty() && $resp_r_player->room_code != $room_code) {
            $this->error("您已经加入了另外一个房间，无法报名其他比赛");
        }

        // 没有任何记录的玩家 - 那就给她记录一下
        if ($resp_rooms->isEmpty() && $resp_r_player->isEmpty()){
            // 获取房间信息 - 判断状态、人数、密码
            $resp_room_info = RoomsModel::GetInfoByKeyword('room_code', $room_code, '1');
            if ($resp_room_info->isEmpty()) {
                $this->error("赛事已经开始，游戏途中无法加入");
            }
            if ($resp_room_info->room_player_num >= 12) {
                $this->error("赛事房间内座位已满，无法加入");
            }
            if ($resp_room_info->is_password == '1' && $resp_room_info->room_password != $room_pass) {

                $this->error("密码核验失败，无法加入$resp_room_info->room_password - $room_pass");
            }

            // 新增 bakal_rooms_player
            if (!RoomsPlayerModel::SaveInsertInfo([
                'room_id' => $resp_room_info->id,
                'room_code' => $resp_room_info->room_code,
                'player_id' => $request->usersId,
                'player_code' => $request->usersCode,
                'create_time' => time(),
            ])){
                $this->error('报名比赛失败，请联系管理员【RoomsPlayerModel::SaveInsertInfo】');
            } else {
                // 新增成功 - 修改 bakal_rooms 人数
                RoomsModel::IncByKeyword('id', $resp_room_info->id);
            }
        }

        // 一直到这里都不需要 socket，info api 才需要，因为那个是核验、也就是前端进入了房间页面
        $this->success();
    }


    /**
     * @param Request $request
     * @param RPlayerValid $valid
     */
    public function edit(Request $request, RPlayerValid $valid) {
        if(!$valid->scene('edit')->check($request->post())){
            $this->error($valid->getError());
        }

        $room_code = $request->post('room_code');
        $params = $request->post(['room_code', 'career_name','career', 'transfer', 'cover']);


        $resp_r_player = RoomsPlayerModel::HasJoinRoomByPlayerId($request->usersId, $this->field);
        if ($resp_r_player->isEmpty()) {
            $this->error("您并未报名本场比赛", null, 302);
        }

        // 修改
        RoomsPlayerModel::SaveEditByKeywordTwo('room_code', $room_code, 'player_code', $request->usersCode, $params);

        $service = new GetewayService();
        // 发送玩家列表
        $player_list = RoomsPlayerModel::GetPlayerListByKeyword('room_code', $room_code);
        if (!$service->SendGroupMsg($room_code, $player_list->toArray(), 'player_list')) {
            $this->error($service->error_msg.'【$service->SendGroupMsg】');
        }

        // 发送玩家信息
        $player_info = RoomsPlayerModel::GetPersonInfo('bakal_rooms_player.player_code', $request->usersCode);
        if (!$service->SendUidMsg($request->usersCode, $player_info->toArray(), 'player_info')) {
            $this->error($service->error_msg.'【$service->SendUidMsg】');
        }

        $this->success($resp_r_player);
    }


    /**
     * @param Request $request
     * @param RPlayerValid $valid
     */
    public function info(Request $request, RPlayerValid $valid) {
        if(!$valid->scene('info')->check($request->post())){
            $this->error($valid->getError());
        }

        $client_id = $request->post('client_id');
        $room_code = $request->post('room_code');

        $resp_r_player = RoomsPlayerModel::HasJoinRoomByPlayerId($request->usersId, $this->field);
        if ($resp_r_player->isEmpty()) {
            $this->error("您并未报名本场比赛", null, 302);
        }

        $service = new GetewayService();
        // 绑定
        if (!$service->BindPlayer($client_id, $request->usersCode)) {
            $this->error($service->error_msg.'【$service->BindPlayer】');
        }
        // 加入房间
        if (!$service->JoinRoom($client_id, $room_code)) {
            $this->error($service->error_msg.'【$service->JoinRoom】');
        }
        // 发送房间信息
        $room_info = RoomsModel::GetInfoByKeyword('room_code', $room_code, 'all', 'field');
        if (!$service->SendGroupMsg($room_code, $room_info->toArray(), 'room_info')) {
            $this->error($service->error_msg.'【$service->SendGroupMsg】');
        }
        // 发送玩家列表
        $player_list = RoomsPlayerModel::GetPlayerListByKeyword('room_code', $room_code);
        if (!$service->SendGroupMsg($room_code, $player_list->toArray(), 'player_list')) {
            $this->error($service->error_msg.'【$service->SendGroupMsg】');
        }

        $this->success($resp_r_player);
    }


    /**
     * @param Request $request
     * @param RPlayerValid $valid
     */
    public function leave(Request $request, RPlayerValid $valid) {
        if(!$valid->scene('leave')->check($request->post())){
            $this->error($valid->getError());
        }
        $room_code = $request->post('room_code');

        $resp_room_info = RoomsModel::GetInfoByKeyword('room_code', $room_code);
        if ($resp_room_info->isEmpty() && $resp_room_info->room_status != '1' && $resp_room_info->room_status != '3') {
            $this->error('赛事已开始，中途不允许退出');
        }

        if ($resp_room_info->room_status == '1') {
            // 啥也不管，反正机制是只能同时参加一次比赛， 所以符合条件的全部修改，不论几个
            if (!RoomsPlayerModel::DeleteInfo($room_code, $request->usersCode)) {
                $this->error("系统错误，请联系管理员【RoomsPlayerModel::SaveEditByKeyword】");
            }
        } else {
            if (!RoomsPlayerModel::SaveEditByKeyword('player_code', $request->usersCode, [
                'status' => '0'
            ])) {
                $this->error("系统错误，请联系管理员【RoomsPlayerModel::SaveEditByKeyword】");
            }
        }
        // 修改房间内 参与人数
        if (!RoomsModel::DecByKeyword('room_code', $room_code)) {
            $this->error("系统错误，请联系管理员【RoomsModel::IncByKeyword】");
        }

        // socket 断开链接
        $service = new GetewayService();
        if (!$service->LeaveRooms($request->usersCode, $room_code)) {
            $this->error($service->error_msg.'【$service->LeaveRooms】');
        }
        // 有人离开房间，推送新的房间内玩家列表
        $player_list = RoomsPlayerModel::GetPlayerListByKeyword('room_code', $room_code);
        if (!$service->SendGroupMsg($room_code, $player_list->toArray(), 'player_list')) {
            $this->error($service->error_msg.'【$service->SendGroupMsg】');
        }

        $this->success();
    }





























}